package com.diorsunion.hedge.bo.stockdatainit;

import com.diorsunion.hedge.enums.Period;
import com.diorsunion.hedge.dal.entity.stock.Stock;
import com.diorsunion.hedge.dal.entity.stock.StockPrice;
import com.diorsunion.hedge.dal.repository.stock.StockPriceRepository;
import com.diorsunion.hedge.dal.repository.stock.StockRepository;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 这个随机算法只适用于 正反指数股
 *
 * @author harley-dog on 2015/7/23.
 */
@Service(value = "RealStockPriceInit")
public class RealStockPriceInit implements StockPriceInit {

    @Resource
    StockPriceRepository repository;

    @Resource
    StockRepository stockRepository;

    @Override
    public List<Date> init(Date begin, Date end, Stock... stocks) {
        return init(begin,end,Lists.newArrayList(stocks));
    }

    @Override
    public List<Date> init(Date begin, Date end, List<Stock> stockList) {
        final Set<Date> datesSet = Sets.newHashSet();
        final List<Date> dateList = Lists.newArrayList();
        stockList.forEach(stock -> {
            Set<Date> dateSets = init(begin, end, stock);
            datesSet.addAll(dateSets);
        });
        dateList.addAll(datesSet);
        dateList.sort((a, b) -> a.compareTo(b));
        return dateList;
    }

    public Set<Date> init(Date begin, Date end, Stock stock) {
        if (stock.name == null || stock.syncEndDate == null) {
            Stock stock_db = stockRepository.get(stock.code);
            stock.name = stock_db.name;
            stock.code = stock_db.code;
            stock.syncEndDate = stock_db.syncEndDate;
            stock.exchange = stock_db.exchange;
        }

        Set<Date> datesSets = Sets.newHashSet();
        List<StockPrice> stockPrices = repository.findStockPrice(stock, begin, end, Period.day);
        stockPrices.forEach(stockPrice -> {
            stock.setStockPrice(stockPrice.thedate, stockPrice);
            datesSets.add(stockPrice.thedate);
        });
        return datesSets;
    }
}
